//
//  WeiboViewController.m
//  iTaoHD
//
//  Created by liunian on 13-12-6.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "WeiboViewController.h"
#import "MBProgressHUD.h"
#import "SNSManager.h"
#define kTextViewLeftMargin 7.0
#define kLeftMargin 14.0

#define kPopViewSizeWidth   540

#define kDefaultShareText @"请填入您要分享的内容！"

#define kSinaButtonTag 1212
#define kTxButtonTag (1212 + 1)
#define kQzoneButtonTag (1212 + 2)
#define kBackButtonTag (1212 + 3)

@interface WeiboViewController ()<SNSManagerDelegate,UITextViewDelegate>{
    NSInteger       _numOfShare;
    BOOL            _isSendViewPoint;
}
@property (nonatomic, retain) CuzyTBKItem     *item;
@property (nonatomic, retain) MBProgressHUD *progressHUD;
@property (nonatomic, retain) UIImageView   *navImageView;
@property (nonatomic, retain) UITextView    *shareTextView;
@property (nonatomic, retain) UILabel       *contentLabel;
@property (nonatomic, retain) UIButton      *sinaButton;
@property (nonatomic, retain) UIButton      *txButton;
//@property (nonatomic, retain) UIButton      *qzoneButton;
@property (nonatomic, retain) UIImageView   *sinaImage;
@property (nonatomic, retain) UIImageView   *txImage;
//@property (nonatomic, retain) UIImageView   *qzoneImage;
@property (nonatomic, retain) UIImageView   *contentImage;
@property (nonatomic, retain) UIScrollView  *contentScroll;
@property (nonatomic, retain) UIButton      *deleteButton;
@property (nonatomic, retain) UILabel       *numberLabel;
@property (nonatomic, copy) NSString        *infoString;
@end

@implementation WeiboViewController

- (void)dealloc{
    [[DataEnvironment sharedDataEnvironment] setWeiboViewController:nil];
}

- (id)initWithCuzyItem:(CuzyTBKItem *)item image:(UIImage *)image infoString:(NSString *)infoString
{
    self = [super init];
    if (self)
    {
        self.item = item;
        self.infoString = infoString;
        if (!infoString) {
            self.infoString = kLinkAPPSite;
        }
        
        self.contentImage.image = image;
        [[DataEnvironment sharedDataEnvironment] setWeiboViewController:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_RGB(255.0f, 255.0f, 255.0f);
    
    [self.view addSubview:self.navImageView];
    
    [self.view addSubview:self.contentScroll];
    
    self.shareTextView.text = kDefaultShareText;
    
    if ([[SNSManager sharedManager] isLoggedInFor:kOFTypeSina])
    {
        self.sinaButton.selected = YES;
        self.sinaImage.image = IMGNAMED(@"icon_sina.png");
    }
    else
    {
        self.sinaButton.selected = NO;
        self.sinaImage.image = IMGNAMED(@"icon_sina_gray.png");
    }
    if ([[SNSManager sharedManager] isLoggedInFor:kOFTypeTX])
    {
        self.txButton.selected = YES;
        self.txImage.image = IMGNAMED(@"icon_tx.png");
    }
    else
    {
        self.txButton.selected = NO;
        self.txImage.image = IMGNAMED(@"icon_tx_gray.png");
    }
//    if ([[SNSManager sharedManager] isLoggedInFor:kOFTypeQZone])
//    {
//        self.qzoneButton.selected = YES;
//        self.qzoneImage.image = IMGNAMED(@"icon_qzone.png");
//    }
//    else
//    {
//        self.qzoneButton.selected = NO;
//        self.qzoneImage.image = IMGNAMED(@"icon_qzone_gray.png");
//    }
    
    NSMutableString *content = nil;
    if (content == nil)
    {
        content = [[NSMutableString alloc] init];
        [content setString:[NSString stringWithFormat:@"//【%@】(%@)",self.item.itemName,self.infoString]];
    }

    self.contentLabel.text = content;
    
    self.numberLabel.text = [NSString stringWithFormat:@"您还可以录入%d字！",140 - [Util countWord:self.contentLabel.text]];
    
    CGSize size = [self.contentLabel.text sizeWithFont:self.contentLabel.font
                                     constrainedToSize:CGSizeMake(kPopViewSizeWidth - 2 * kLeftMargin, 8000)];
    self.contentLabel.frame = CGRectMake(kLeftMargin,
                                         self.sinaButton.frame.origin.y + self.sinaButton.frame.size.height + 10,
                                         size.width,
                                         size.height);
    
    UIImage *image = self.contentImage.image;
    self.contentImage.frame = CGRectMake(kLeftMargin,
                                         self.contentLabel.frame.origin.y + self.contentLabel.frame.size.height + 10,
                                         self.contentImage.frame.size.width,
                                         (image==nil || image.size.width == 0)?0:
                                         self.contentImage.frame.size.width * image.size.height/image.size.width);
    if (image != nil)
    {
        self.deleteButton.center = CGPointMake(self.contentImage.frame.origin.x + self.contentImage.frame.size.width, self.contentImage.frame.origin.y);
    }
    else
    {
        [self.deleteButton removeFromSuperview];
    }
    self.contentScroll.contentSize = CGSizeMake(kPopViewSizeWidth, self.contentImage.frame.origin.y + self.contentImage.frame.size.height + 20);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)finish
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - Getter Methods
- (UIImageView *)navImageView{
    if (!_navImageView) {
        UIImage  *img = IMGNAMED(@"bg_nav_modal.png");
        img = [img stretchableImageWithLeftCapWidth:floor(img.size.width/2) topCapHeight:0];
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kPopViewSizeWidth, img.size.height)];
        _navImageView.backgroundColor = [UIColor clearColor];
        _navImageView.userInteractionEnabled = YES;
        _navImageView.image = img;
        
        UILabel  *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kPopViewSizeWidth, img.size.height)];
        title.backgroundColor = [UIColor clearColor];
        title.textColor = COLOR_RGB(0, 0, 0);
        title.textAlignment = UITextAlignmentCenter;
        title.font = FONT_TITLE(26.0f);
        title.text = @"分享";
        [_navImageView addSubview:title];
        
        img = IMGNAMED(@"bg_nav_button_small.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floor((_navImageView.frame.size.height - img.size.height)/2), img.size.width, img.size.height);
        [back setBackgroundImage:img forState:UIControlStateNormal];
        [back setTitleColor:COLOR_RGB(0,0,0) forState:UIControlStateNormal];
        [back setTitle:@"关闭" forState:UIControlStateNormal];
        back.titleLabel.font = FONT_CONTENT(16.0f);
        [back addTarget:self action:@selector(finish) forControlEvents:UIControlEventTouchUpInside];
        [_navImageView addSubview:back];
        
        UIButton *send = [UIButton buttonWithType:UIButtonTypeCustom];
        send.exclusiveTouch = YES;
        send.frame = CGRectMake(kPopViewSizeWidth - img.size.width - 10, floor((_navImageView.frame.size.height - img.size.height)/2), img.size.width, img.size.height);
        [send setBackgroundImage:img forState:UIControlStateNormal];
        [send setTitleColor:COLOR_RGB(0,0,0) forState:UIControlStateNormal];
        [send setTitle:@"分享" forState:UIControlStateNormal];
        send.titleLabel.font = FONT_CONTENT(16.0f);
        [send addTarget:self
                 action:@selector(forwardButtonPressed:)
       forControlEvents:UIControlEventTouchUpInside];
        [_navImageView addSubview:send];
    }
    return _navImageView;
}

- (MBProgressHUD *)progressHUD
{
    if (!_progressHUD) {
        _progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
        _progressHUD.labelFont = FONT_CONTENT(18.0);
        _progressHUD.labelText = @"正在发送...";
        [self.view addSubview:_progressHUD];
    }
    return _progressHUD;
}

- (void)forwardButtonPressed:(id)sender
{
    if (self.sinaButton.selected == NO && self.txButton.selected == NO)
    {
        [Util showWarningTipsView:@"请选择需要转发的账号！"];
        return;
    }
    
    NSString *content = [self.shareTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([content isEqualToString:kDefaultShareText])
    {
        content = @"";
    }
    NSString *text = [NSString stringWithFormat:@"%@ %@",content,self.contentLabel.text];
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (text == nil || [text length] == 0)
    {
        [Util showWarningTipsView:@"发送的内容不能为空！"];
        return;
    }
    
    if ([Util countWord:text] > 140)
    {
        [Util showWarningTipsView:@"发送内容过长！"];
        return;
    }
    

    //判断是否需要发观点
    _numOfShare = 0;
    [self.progressHUD startAnimating];
    
    NSInteger maxLength = 140;
    if (maxLength <= 0 || maxLength > 140)
    {
        maxLength = 140;
    }
    NSMutableString *last = [[NSMutableString alloc] init];
    
    if (self.sinaButton.selected)
    {
        _numOfShare++;
        [last setString:text];
        [[SNSManager sharedManager] sendContentWithText:last image:self.contentImage.image delegate:self forType:kOFTypeSina];

    }
    
    if (self.txButton.selected)
    {
        _numOfShare++;
        [last setString:text];
        [[SNSManager sharedManager] sendContentWithText:last image:self.contentImage.image delegate:self forType:kOFTypeTX];
    }

}


- (UILabel *)numberLabel
{
    if (!_numberLabel)
    {
        _numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(kTextViewLeftMargin,
                                                                 self.shareTextView.frame.origin.y + self.shareTextView.frame.size.height + 5,
                                                                 kPopViewSizeWidth - 2 * kTextViewLeftMargin,
                                                                 25)];
        _numberLabel.backgroundColor = [UIColor clearColor];
        _numberLabel.font = FONT_CONTENT(16);
        _numberLabel.textColor = COLOR_RGB(114.0, 114.0, 114.0);
        _numberLabel.textAlignment = UITextAlignmentRight;
    }
    return _numberLabel;
}

- (UITextView *)shareTextView
{
    if (!_shareTextView)
    {
        _shareTextView = [[UITextView alloc] initWithFrame:CGRectMake(kTextViewLeftMargin, kTextViewLeftMargin, kPopViewSizeWidth - 2 * kTextViewLeftMargin, 200)];
        _shareTextView.layer.borderColor = COLOR_RGB(217, 217, 217).CGColor;
        _shareTextView.layer.borderWidth = 1;
        _shareTextView.font = FONT_CONTENT(18);
        _shareTextView.textColor = [UIColor blackColor];
        _shareTextView.backgroundColor = [UIColor whiteColor];
        _shareTextView.delegate = self;
    }
    return _shareTextView;
}

- (void)weiboButtonPressed:(id)sender
{
    UIButton *pressButton = (UIButton *)sender;
    
    switch (pressButton.tag)
    {
        case kSinaButtonTag:
            if ([[SNSManager sharedManager] isLoggedInFor:kOFTypeSina])
            {
                self.sinaButton.selected = !self.sinaButton.selected;
            }
            else
            {
                [self.shareTextView resignFirstResponder];
                [[SNSManager sharedManager] loginFor:kOFTypeSina withDelegate:self];
            }
            break;
        case kTxButtonTag:
            if ([[SNSManager sharedManager] isLoggedInFor:kOFTypeTX])
            {
                self.txButton.selected = !self.txButton.selected;
            }
            else
            {
                [self.shareTextView resignFirstResponder];
                [[SNSManager sharedManager] loginFor:kOFTypeTX withDelegate:self];
            }
            break;
//        case kQzoneButtonTag:
//            if ([[SNSManager sharedManager] isLoggedInFor:kOFTypeQZone])
//            {
//                self.qzoneButton.selected = !self.qzoneButton.selected;
//            }
//            else
//            {
//                [self.shareTextView resignFirstResponder];
//               [[SNSManager sharedManager] loginFor:kOFTypeQZone withDelegate:self];
//            }
//            break;
        default:
            break;
    }
}

- (UIButton *)sinaButton
{
    if (!_sinaButton)
    {
        _sinaButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _sinaButton.tag = kSinaButtonTag;
        [_sinaButton setImage:IMGNAMED(@"bg_check_unchecked.png") forState:UIControlStateNormal];
        [_sinaButton setImage:IMGNAMED(@"bg_check_checked.png") forState:UIControlStateSelected];
        [_sinaButton setTitle:@"        " forState:UIControlStateNormal];
        [_sinaButton addTarget:self
                        action:@selector(weiboButtonPressed:)
              forControlEvents:UIControlEventTouchUpInside];
        [self.contentScroll addSubview:_sinaButton];
    }
    return _sinaButton;
}

- (UIButton *)txButton
{
    if (!_txButton)
    {
        _txButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _txButton.tag = kTxButtonTag;
        [_txButton setImage:IMGNAMED(@"bg_check_unchecked.png") forState:UIControlStateNormal];
        [_txButton setImage:IMGNAMED(@"bg_check_checked.png") forState:UIControlStateSelected];
        [_txButton setTitle:@"        " forState:UIControlStateNormal];
        [_txButton addTarget:self
                      action:@selector(weiboButtonPressed:)
            forControlEvents:UIControlEventTouchUpInside];
        [self.contentScroll addSubview:_txButton];
    }
    return _txButton;
}

//- (UIButton *)qzoneButton
//{
//    if (!_qzoneButton)
//    {
//        _qzoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        _qzoneButton.tag = kQzoneButtonTag;
//        [_qzoneButton setImage:IMGNAMED(@"bg_check_unchecked.png") forState:UIControlStateNormal];
//        [_qzoneButton setImage:IMGNAMED(@"bg_check_checked.png") forState:UIControlStateSelected];
//        [_qzoneButton setTitle:@"        " forState:UIControlStateNormal];
//        [_qzoneButton addTarget:self
//                         action:@selector(weiboButtonPressed:)
//               forControlEvents:UIControlEventTouchUpInside];
//        [self.contentScroll addSubview:_qzoneButton];
//    }
//    return _qzoneButton;
//}

- (UIImageView *)sinaImage
{
    if (!_sinaImage)
    {
        _sinaImage = [[UIImageView alloc] init];
        [self.contentScroll addSubview:_sinaImage];
    }
    return _sinaImage;
}

- (UIImageView *)txImage
{
    if (!_txImage)
    {
        _txImage = [[UIImageView alloc] init];
        [self.contentScroll addSubview:_txImage];
    }
    return _txImage;
}

//- (UIImageView *)qzoneImage
//{
//    if (!_qzoneImage)
//    {
//        _qzoneImage = [[UIImageView alloc] init];
//        [self.contentScroll addSubview:_qzoneImage];
//    }
//    return _qzoneImage;
//}

- (UILabel *)contentLabel
{
    if (!_contentLabel)
    {
        _contentLabel = [[UILabel alloc] init];
        _contentLabel.numberOfLines = 0;
        _contentLabel.backgroundColor = [UIColor clearColor];
        _contentLabel.font = FONT_CONTENT(15);
        _contentLabel.textColor = COLOR_RGB(20, 20, 20);
    }
    return _contentLabel;
}

- (UIImageView *)contentImage
{
    if (!_contentImage)
    {
        _contentImage = [[UIImageView alloc] initWithFrame:CGRectMake(kLeftMargin,
                                                                      0,
                                                                      455,
                                                                      0)];
        _contentImage.image = nil;
    }
    return _contentImage;
}

- (UIScrollView *)contentScroll
{
    if (!_contentScroll)
    {
        _contentScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 70, kPopViewSizeWidth, 550)];
        _contentScroll.backgroundColor = [UIColor clearColor];
        _contentScroll.userInteractionEnabled = YES;
        
        [_contentScroll addSubview:self.shareTextView];
        [_contentScroll addSubview:self.numberLabel];
        
        UIImage *image = IMGNAMED(@"bg_pointline.png");
        UIImageView *lineView = [[UIImageView alloc] initWithImage:image];
        lineView.frame = CGRectMake(kTextViewLeftMargin,
                                    self.numberLabel.frame.origin.y + self.numberLabel.frame.size.height + 10,
                                    kPopViewSizeWidth - 2 * kTextViewLeftMargin,1);
        [self.contentScroll addSubview:lineView];
        
        [self sinaImage];
        [self txImage];
//        [self qzoneImage];
    
        self.sinaButton.frame = CGRectMake(kLeftMargin,
                                           lineView.frame.origin.y + lineView.frame.size.height,
                                           70, 36);
        self.sinaImage.frame = CGRectMake(self.sinaButton.frame.origin.x + 27,
                                          self.sinaButton.frame.origin.y,
                                          30, 30);
        
        self.txButton.frame = CGRectMake(kLeftMargin + self.sinaButton.frame.size.width + 5,
                                         lineView.frame.origin.y + lineView.frame.size.height,
                                         self.sinaButton.frame.size.width,
                                         self.sinaButton.frame.size.height);
        self.txImage.frame = CGRectMake(self.txButton.frame.origin.x + 28,
                                        self.txButton.frame.origin.y + 4,
                                        30, 30);
        
//        self.qzoneButton.frame = CGRectMake(kLeftMargin + 2 *(self.sinaButton.frame.size.width + 5),
//                                            lineView.frame.origin.y + lineView.frame.size.height,
//                                            self.sinaButton.frame.size.width,
//                                            self.sinaButton.frame.size.height);
//        self.qzoneImage.frame = CGRectMake(self.qzoneButton.frame.origin.x + 22,
//                                           self.qzoneButton.frame.origin.y + 2,
//                                           30, 30);
    
        lineView = [[UIImageView alloc] initWithImage:image];
        lineView.frame = CGRectMake(kTextViewLeftMargin,
                                    self.sinaButton.frame.origin.y + self.sinaButton.frame.size.height,
                                    kPopViewSizeWidth - 2 * kTextViewLeftMargin,
                                    1);
        [self.contentScroll addSubview:lineView];
        
        [_contentScroll addSubview:self.contentLabel];
        [_contentScroll addSubview:self.contentImage];
        [_contentScroll addSubview:self.deleteButton];
    }
    return _contentScroll;
}

- (void)deleteImage:(id)sender
{
    [self.deleteButton removeFromSuperview];
    
    self.contentScroll.contentSize = CGSizeMake(self.contentScroll.contentSize.width,
                                                self.contentScroll.contentSize.height - self.contentImage.frame.size.height);
    
    self.contentImage.image = nil;
    [self.contentImage removeFromSuperview];
}

- (UIButton *)deleteButton
{
    if (!_deleteButton)
    {
        _deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleteButton setImage:IMGNAMED(@"btn_close_act.png") forState:UIControlStateNormal];
        _deleteButton.frame = CGRectMake(0, 0, 40, 40);
        [_deleteButton addTarget:self
                          action:@selector(deleteImage:)
                forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteButton;
}

#pragma mark - SNSManagerDelegate

- (void)snsManagerLoginDidSuccessFor:(OFTypeE)type{
    switch (type)
    {
        case kOFTypeSina:
            self.sinaImage.image = IMGNAMED(@"icon_sina.png");
            self.sinaButton.selected = YES;
            break;
        case kOFTypeTX:
            self.txImage.image = IMGNAMED(@"icon_tx.png");
            self.txButton.selected = YES;
            break;
//        case kOFTypeQZone:
//            self.qzoneImage.image = IMGNAMED(@"icon_qzone.png");
//            self.qzoneButton.selected = YES;
//            break;
        default:
            break;
    }
}
- (void)snsManagerLoginDidFailFor:(OFTypeE)type{

}
- (void)snsManagerLogoutDidFinishFor:(OFTypeE)type{

}

//token Expired callback
- (void)snsManagerAuthorizeExpired{
}

//UserProfile callback
- (void)snsManagerUserProfileDidFailFor:(OFTypeE)type{}
- (void)snsManagerUserProfileDidSuccessFor:(OFTypeE)type withResult:(id)result{}

//Shorten Url
- (void)snsManagerShortenUrlDidFailFor:(OFTypeE)type{}
- (void)snsManagerShortenUrlDidSuccessFor:(OFTypeE)type withResult:(id)result{}

//share content
- (void)snsManagerShareContentDidSuccessFor:(OFTypeE)type weiboId:(NSString *)weiboId{
    if (_isSendViewPoint)
    {
        //需要转发观点
        if (self.sinaButton.selected)
        {
            if (type == kOFTypeSina)
            {
                _isSendViewPoint = NO;
                NSString *content = [self.shareTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

            }
        }
        else if (self.txButton.selected)
        {
            if (type == kOFTypeTX)
            {
                _isSendViewPoint = NO;
                NSString *content = [self.shareTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

            }
        }
//        else if (self.qzoneButton.selected)
//        {
//            if (type == kOFTypeQZone)
//            {
//                _isSendViewPoint = NO;
//                NSString *content = [self.shareTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//
//            }
//        }
    }
    _numOfShare--;
    
    switch (type)
    {
        case kOFTypeTX:
//            [BUUtil showTipsView:@"转发腾讯微博成功！"];
            break;
        case kOFTypeSina:
//            [BUUtil showTipsView:@"转发新浪微博成功！"];
            break;
        case kOFTypeQZone:
//            [BUUtil showTipsView:@"转发QQ空间成功！"];
            break;
        default:
            break;
    }
    if (_numOfShare == 0)
    {
        [self.progressHUD stopAnimating];
        [self finish];
    }

}

#pragma mark - UITextView delegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:kDefaultShareText])
    {
        textView.text = @"";
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    NSString *text = [NSString stringWithFormat:@"%@ %@",self.shareTextView.text,self.contentLabel.text];
    NSInteger num = 140 - [Util countWord:text];
    if (num >= 0)
    {
        self.numberLabel.text = [NSString stringWithFormat:@"您还可以录入%d字！",num];
    }
    else
    {
        self.numberLabel.text = [NSString stringWithFormat:@"已超出%d字",-num];
    }
}


@end
